package config

import (
	"log"
	"time"
	"wisdomCoach/global"

	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"gorm.io/gorm/logger"
)

func initMySQL() {
	dsn := viper.GetString("mysql.dsn")
	newLogger := logger.New(
		log.New(log.Writer(), "\r\n", log.LstdFlags), // io writer
		logger.Config{
			SlowThreshold: time.Second, // 慢 SQL 阈值
			LogLevel:      logger.Info, // 日志级别
			Colorful:      true,        // 彩色打印
		},
	)
	db, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
		Logger: newLogger})
	if err != nil {
		log.Fatalf("数据库链接失败: %v", err)
	}
	sqlDB, err := db.DB()
	sqlDB.SetMaxIdleConns(viper.GetInt("mysql.maxIdleConn"))
	sqlDB.SetMaxOpenConns(viper.GetInt("mysql.maxOpenConns"))
	sqlDB.SetConnMaxLifetime(time.Hour)
	if err != nil {
		log.Fatalf("连接池构建失败: %v", err)
	}
	global.DB = db
}
